<?PHP

if(!class_exists('op_WordPress')){
class op_WordPress{
	function load(){
		global $wpdb;
		ob_start();
		$root_path = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))));
		
		global $pagenow;
		if(!function_exists('make_clickable') || $pagenow == 'wp-login.php'){
			require_once($root_path . '/wp-login.php');
		}
		else{
			define('ABSPATH',$root_path . '/');
			
			// Eval chain to fix make_clickable conflict
			$include_login_contents = file_get_contents($root_path . '/wp-login.php');
			$include_login_contents = preg_replace('/^\<\?php/','',$include_login_contents);
			$include_login_contents = preg_replace('/\?\>$/','',$include_login_contents);
		
			$include_formatting_contents = file_get_contents($root_path . '/wp-includes/formatting.php');
			$include_formatting_contents = preg_replace('/^\<\?php/','',$include_formatting_contents);
			$include_formatting_contents = preg_replace('/\?\>$/','',$include_formatting_contents);
			$include_formatting_contents = str_replace('make_clickable','op_make_clickable',$include_formatting_contents);
			
			$include_settings_contents = file_get_contents($root_path . '/wp-settings.php');
			$include_settings_contents = preg_replace('/^\<\?php/','',$include_settings_contents);
			$include_settings_contents = preg_replace('/\?\>$/','',$include_settings_contents);
			
			// Do not load plug-ins.  Plug-ins are not needed for OnePress auth
			// Some plug-ins such as redirection and disqus have been found to create issues with the phpBB login
			$include_settings_contents = str_replace('$current_plugins = get_option(\'active_plugins\');','$current_plugins = array();',$include_settings_contents);
			
			$include_settings_contents = str_replace('require (ABSPATH . WPINC . \'/formatting.php\');',$include_formatting_contents,$include_settings_contents);
			
			$include_config_contents = trim(file_get_contents($root_path . '/wp-config.php'));
			$include_config_contents = preg_replace("/require_once\s*\(\s*ABSPATH\s*\.\s*'wp-settings.php'\s*\);/",$include_settings_contents,$include_config_contents);
			$include_config_contents = preg_replace('/^\<\?php/','',$include_config_contents);
			$include_config_contents = preg_replace('/\?\>$/','',$include_config_contents);
			
			$include_load_contents = file_get_contents($root_path . '/wp-load.php');
			$include_load_contents = preg_replace('/^\<\?php/','',$include_load_contents);
			$include_load_contents = preg_replace('/\?\>$/','',$include_load_contents);

			$include_load_contents = str_replace('define( \'ABSPATH\', dirname(__FILE__) . \'/\' );','',$include_load_contents);
			$include_load_contents = str_replace('require_once( ABSPATH . \'wp-config.php\' );',$include_config_contents,$include_load_contents);
			$include_load_contents = str_replace('require_once( dirname(ABSPATH) . \'/wp-config.php\' );',$include_config_contents,$include_load_contents);

			$include_login_contents = str_replace('require( dirname(__FILE__) . \'/wp-load.php\' );',$include_load_contents,$include_login_contents);

			eval($include_login_contents);
			// End eval chain
		}
		ob_end_clean();
	}
	
	function loadAdminAPI(){
		if(!function_exists('validate_username')){
			require_once(ABSPATH . '/wp-admin/includes/admin.php');
		}
		else{
			$include_registration_contents = file_get_contents(ABSPATH . WPINC . '/registration.php');
			$include_registration_contents = preg_replace('/^\<\?php/','',$include_registration_contents);
			$include_registration_contents = preg_replace('/\?\>$/','',$include_registration_contents);
			$include_registration_contents = str_replace('validate_username','op_validate_username',$include_registration_contents);
			
			$include_admin_contents = file_get_contents(ABSPATH . '/wp-admin/includes/admin.php');
			$include_admin_contents = preg_replace('/^\<\?php/','',$include_admin_contents);
			$include_admin_contents = preg_replace('/\?\>$/','',$include_admin_contents);
			$include_admin_contents = str_replace('require_once(ABSPATH . WPINC . \'/registration.php\');',$include_registration_contents,$include_admin_contents);
			
			eval($include_admin_contents);
		}
	}
	
	function addUser($user){
		global $wpdb;
		mysql_select_db(DB_NAME);  // Select WP database
		
		// Derived from wp_insert_user() wp-includes/registration.php line 104
		$user_login = sanitize_user( $user['username'] );
		$user_login = apply_filters('pre_user_login', $user_login);
		$user_login = $wpdb->escape($user_login);

		$user_nicename = sanitize_title( $user_login );
		$user_nicename = apply_filters('pre_user_nicename', $user_nicename);
		
		$user_url = '';

		$user_email = $user['email'] ? $wpdb->escape($user['email']) : '';
		
		$display_name = $user_login;
		
		$user_registered = gmdate('Y-m-d H:i:s');
		
		$user_pass = wp_hash_password($user['password']);
		
		$data = compact( 'user_pass', 'user_email', 'user_login', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
		$wpdb->insert( $wpdb->users, $data);
		$user_id = (int) $wpdb->insert_id;
		
		$wp_user = new WP_User($user_id);
		$wp_user->set_role(get_option('default_role'));
		
		return $wp_user;
	}
	
	function logout(){
		op_WordPress::load();
		wp_clear_auth_cookie();
	}
	
	function updateUser($data){
		$user = '';
		$user->ID = op_WordPress::getIdByName($data['username']);
		$user->user_login = $data['username'];
		$user->user_pass = $data['new_password'];
		$user->user_email = $data['email'];
		
		wp_update_user(get_object_vars($user));
	}
	
	function getIdByName($user){
		mysql_select_db(DB_NAME);
		return get_profile('id',$user);
	}
	
	function op_init(){
		
		// Add template hooks
		add_action('op_pre_main',array('op_WordPress','load_layout_template'),10,2);

		global $pagenow;
	
		if (isset($_REQUEST["action"])) {
			$action = $_REQUEST["action"];
		}
		else if($pagenow == "wp-login.php"){
			$action = 'login';
		}
		else if($pagenow == 'profile.php'){
			$action = 'profile';
		}

		if(in_array($action, array('lostpassword','retrievepassword','register','login','profile','update'))){
			if($pagenow == 'profile.php'  && $action == 'update') $action = 'profile';
			
			$data = call_user_func(array('op_WordPress','op_'.$action));
			call_user_func(array('op_WordPress','render'),$action,$data);
			die; // We are done, stop process
		}
		else{
			return;
		}
	}
	
	function load_layout_template($type,$data){

		switch($type){
			case 'login':
				include(TEMPLATEPATH.'/template.login.php');
				break;
			
			case 'register':
				include(TEMPLATEPATH.'/template.register.php');
				break;
			
			case 'lostpassword':
				include(TEMPLATEPATH.'/template.lostpassword.php');
				break;
				
			case 'profile':
				include(TEMPLATEPATH.'/template.profile.php');
				break;
		}
	}
	
	function op_login(){
		if ( isset( $_REQUEST['redirect_to'] ) )
			$redirect_to = $_REQUEST['redirect_to'];
		else
			$redirect_to = admin_url();
	
		if ( is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) )
			$secure_cookie = false;
		else
			$secure_cookie = '';
	
		$user = wp_signon('', $secure_cookie);
		
		$redirect_to = apply_filters('login_redirect', $redirect_to, isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '', $user);
	
		if ( !is_wp_error($user) ) {
			if ( !$user->has_cap('edit_posts') && ( empty( $redirect_to ) || strpos($redirect_to,'wp-admin/') )){
				$redirect_to = admin_url('profile.php');
			}
			wp_safe_redirect($redirect_to);
			exit();
		}
	
		$errors = $user;
		// Clear errors if loggedout is set.
		if ( !empty($_GET['loggedout']) )
			$errors = new WP_Error();
		
		return array('redirect_to'=>$redirect_to,'errors'=>$errors);
	}
	
	function op_register(){
		if ( !get_option('users_can_register') ) {
			wp_redirect('wp-login.php?registration=disabled');
			exit();
		}
		
		require_once( ABSPATH . WPINC . '/registration.php');
		
		$user_login = '';
		$user_email = '';
		
		$user_login = $_POST['user_login'];
		$user_email = $_POST['user_email'];
		$errors = register_new_user($user_login, $user_email);
		if ( !is_wp_error($errors) ) {
			wp_redirect('wp-login.php?checkemail=registered');
			exit();
		}
		return $errors;
	}
	
	function op_lostpassword(){
		$http_post = ('POST' == $_SERVER['REQUEST_METHOD']);
		if ( $http_post ) {
			$errors = retrieve_password();
			if ( !is_wp_error($errors) ) {
				wp_redirect('wp-login.php?checkemail=confirm');
				exit();
			}
		}
		else{
			$errors = new WP_Error(); // initialize error object
		}

		if ( 'invalidkey' == $_GET['error'] && isset($errors)) $errors->add('invalidkey', __('Sorry, that key does not appear to be valid.'));
	
		do_action('lost_password'); 
		return $errors;
	}
	
	function op_profile(){
		if ( !$user_id ){
			$current_user = wp_get_current_user();
			$user_id = $current_user->ID;
		}
		require_once(ABSPATH.'wp-admin/includes/user.php');
		
		if($_POST['action'] == 'update'){
			require_once(ABSPATH.'wp-admin/includes/admin.php');
			check_admin_referer('update-user_' . $user_id);
			
			do_action('personal_options_update');
			
			$errors = edit_user($user_id);
			
			if( !is_wp_error( $errors ) ) {
				global $wpdb;
				$userdata = get_userdata( $user_id );
				$user_login = $wpdb->escape( $userdata->user_login );
				// is password being changed in wordpress?
				if (!empty($_POST['pass1'])) // using $_POST['pass1'] is ok here because it will not reach this point if value doesn't pass checks in edit_user()
					op_updatePassword($user_login,$_POST['pass1'],'wp');
				
				if(!empty($_POST['email']))
					op_updateEmail($user_login,$_POST['email'],'wp');

				op_selectDbFromModule('wp');
				
				$redirect = add_query_arg('wp_http_referer', urlencode($wp_http_referer), "profile.php");
				wp_redirect($redirect);
				exit;
			}			
		}

		$profileuser = get_user_to_edit($user_id);
		
		return array(
			'is_profile_page'	=>	TRUE,
			'profileuser'		=>	$profileuser,
			'user_id'			=>	$user_id,
			'errors'			=>  $errors
		);
	}
	
	function render($action,$data){
		$url = get_bloginfo('template_directory').'/';
		wp_register_style('opaccount',$url.'account.css');
		wp_enqueue_style('opaccount');

		global $OnePress;
		$OnePress->layout->_registerAllSidebars();
		$OnePress->layout->classname = $action; // override body classname
		get_header();
		$OnePress->layout->load_type = $action;
		$OnePress->layout->render($data);
		get_footer();
	}
}
}

?>
